using System;
using Volo.Abp.Domain.Entities.Auditing;
using Volo.Abp.MultiTenancy;

namespace AuthService.Domain.OAuth;

/// <summary>
/// OAuth授权实体
/// </summary>
public class OAuthAuthorization : FullAuditedEntity<Guid>, IMultiTenant
{
    /// <summary>
    /// 租户ID
    /// </summary>
    public virtual Guid? TenantId { get; set; }

    /// <summary>
    /// 用户ID
    /// </summary>
    public virtual Guid UserId { get; set; }

    /// <summary>
    /// 客户端ID
    /// </summary>
    public virtual Guid ClientId { get; set; }

    /// <summary>
    /// 授权代码
    /// </summary>
    public virtual string AuthorizationCode { get; set; } = string.Empty;

    /// <summary>
    /// 作用域
    /// </summary>
    public virtual string Scopes { get; set; } = string.Empty;

    /// <summary>
    /// 重定向URI
    /// </summary>
    public virtual string RedirectUri { get; set; } = string.Empty;

    /// <summary>
    /// 状态参数
    /// </summary>
    public virtual string State { get; set; } = string.Empty;

    /// <summary>
    /// 代码创建时间
    /// </summary>
    public virtual DateTime CreatedAt { get; set; }

    /// <summary>
    /// 代码过期时间
    /// </summary>
    public virtual DateTime ExpiresAt { get; set; }

    /// <summary>
    /// 是否已被使用
    /// </summary>
    public virtual bool IsUsed { get; set; } = false;

    /// <summary>
    /// 使用时间
    /// </summary>
    public virtual DateTime? UsedAt { get; set; }

    /// <summary>
    /// 是否活跃
    /// </summary>
    public virtual bool IsActive { get; set; } = true;

    /// <summary>
    /// 会话ID
    /// </summary>
    public virtual string SessionId { get; set; } = string.Empty;

    /// <summary>
    /// IP地址
    /// </summary>
    public virtual string IpAddress { get; set; } = string.Empty;

    /// <summary>
    /// 用户代理
    /// </summary>
    public virtual string UserAgent { get; set; } = string.Empty;

    /// <summary>
    /// 授权类型
    /// </summary>
    public virtual string AuthorizationType { get; set; } = string.Empty;

    protected OAuthAuthorization()
    {
    }

    public OAuthAuthorization(Guid id, Guid userId, Guid clientId, string authorizationCode) : base(id)
    {
        UserId = userId;
        ClientId = clientId;
        AuthorizationCode = authorizationCode;
        CreatedAt = DateTime.Now;
        ExpiresAt = DateTime.Now.AddMinutes(10); // 授权码通常10分钟过期
    }

    /// <summary>
    /// 检查授权码是否过期
    /// </summary>
    public virtual bool IsExpired()
    {
        return DateTime.Now > ExpiresAt;
    }

    /// <summary>
    /// 使用授权码
    /// </summary>
    public virtual void UseCode()
    {
        IsUsed = true;
        UsedAt = DateTime.Now;
    }

    /// <summary>
    /// 撤销授权
    /// </summary>
    public virtual void Revoke()
    {
        IsActive = false;
    }
}